package com.hd.trans.ui.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hd.trans.R;
import com.hd.trans.network.ApiServiceManager;
import com.hd.trans.network.RxSchedulers;
import com.hd.trans.network.bean.trans.BaseResponse;
import com.hd.trans.network.bean.trans.QueryTaskStatus;
import com.hd.trans.network.bean.trans.UploadTaskStatus;
import com.hd.trans.share.DownloadArg;
import com.hd.trans.share.FileConfigManager;
import com.hd.trans.share.UrlDownloadRequest;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.ui.service.NetDisposableObserver3;
import com.hd.trans.utils.Base64Util;
import com.hd.trans.utils.FileUtils;
import com.hd.trans.utils.FileUtilsKotlin;
import com.hd.trans.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PictureTransActivity extends BaseActivity {
    private static final long DELAY_MILL = 200;
    private ImageView ivOriginal,ivTrans;
    private TextView tvLog;
    private String taskId;
    private File dstFile;
    private String dstFilePath;
    private boolean uploadFinish;
    private int queryTaskCount;//查询次数统计

    @Override
    protected int getLayoutId() {
        return R.layout.activity_picture_trans;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);
        initView();
        setListener();
        initData();
    }

    private void initData() {
        dstFilePath = FileUtils.getTransFileBasePath()+"for_upload.png";
        dstFile = new File(dstFilePath);
        Log.i("fileName","fileName = "+dstFile.getName());
        if(!dstFile.exists()){
            FileUtilsKotlin.INSTANCE.assetRes2File(
                    getAssets(),
                    "test_trans.png",
                    dstFilePath
            );
        }

        try {
            InputStream ims = getAssets().open("test_trans.png");
            Drawable d = Drawable.createFromStream(ims, null);
            ivOriginal.setImageDrawable(d);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        ivOriginal = findViewById(R.id.iv_original);
        ivTrans = findViewById(R.id.iv_trans);
        tvLog = findViewById(R.id.tv_log);
    }

    private void setListener() {
        findViewById(R.id.btn_create_task).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createTask();
            }
        });
        findViewById(R.id.btn_upload_file).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(taskId)){
                    ToastUtils.showInfo("请先创建任务");
                    return;
                }
                uploadFile();
            }
        });
        findViewById(R.id.btn_query_task).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(uploadFinish){
                    uploadFinish = false;
                    queryTaskCount = 0;
                    mXHandler.removeCallbacks(queryTaskRunnable);
                    mXHandler.postDelayed(queryTaskRunnable,DELAY_MILL);
                }else {
                    ToastUtils.showInfo("请先上传文件");
                }

            }
        });
    }

    private void createTask() {
        Call<String> call = ApiServiceManager.INSTANCE.getTransitionNewApi().createTask();

        //发送网络请求(异步)
        call.enqueue(
                new Callback<String>() {
                    //请求成功时回调
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        taskId = response.body();
                        tvLog.append(taskId);
                        tvLog.append("\n");
                        ToastUtils.showInfo("任务创建成功");
                    }

                    //请求失败时回调
                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        tvLog.append("\n");
                        tvLog.append("连接失败");
                        tvLog.append("\n");
                    }
                }
        );
    }

    private void uploadFile(){
        ApiServiceManager.INSTANCE.getTransitionNewApi().uploadTask(
                "zh",
                "en",
                taskId,
                dstFile.getName(),
                Base64Util.INSTANCE.imageToBase64(dstFilePath),
                false
        )
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver3<>(new NetDisposableObserver3.NetCallBack<BaseResponse<UploadTaskStatus>>() {
                    @Override
                    public void onResponse(BaseResponse<UploadTaskStatus> response) {
                        if (response != null) {
                            uploadFinish = true;
                            tvLog.append("\n");
                            tvLog.append("onResponse:-----------");
                            tvLog.append(response.getData().toString());
                            tvLog.append("\n");
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        tvLog.append("\n");
                        tvLog.append("onError:-----------");
                        tvLog.append(msg);
                        tvLog.append("\n");
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        tvLog.append("\n");
                        tvLog.append("onTokenInvalid:-----------");
                        tvLog.append(msg);
                        tvLog.append("\n");
                    }
                }));
    }

    private Runnable queryTaskRunnable = new Runnable() {
        @Override
        public void run() {
            if(queryTaskCount > 60*1000/DELAY_MILL){//30秒超时
                return;
            }
            queryTask();
        }
    };

    private void queryTask() {
        ApiServiceManager.INSTANCE.getTransitionNewApi().queryTask(taskId)
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new NetDisposableObserver3<>(new NetDisposableObserver3.NetCallBack<BaseResponse<QueryTaskStatus>>() {
                    @Override
                    public void onResponse(BaseResponse<QueryTaskStatus> response) {
                        if (response != null) {
                            if(response.getData().getProgress() == 100){
                                tvLog.append("\n");
                                tvLog.append("onResponse:-----------");
                                tvLog.append(response.getData().toString());
                                tvLog.append("\n");

                                String dstDownloadPath = response.getData().getDstDownload();
                                String saveName = dstDownloadPath.substring(dstDownloadPath.lastIndexOf("/")+1);
                                tvLog.append(saveName);
                                tvLog.append("\n");
                                downloadFile(dstDownloadPath,saveName);
                            }else {
                                mXHandler.removeCallbacks(queryTaskRunnable);
                                mXHandler.postDelayed(queryTaskRunnable,DELAY_MILL);
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        tvLog.append("\n");
                        tvLog.append("onError:-----------");
                        tvLog.append(msg);
                        tvLog.append("\n");
                    }

                    @Override
                    public void onTokenInvalid(String msg) {
                        tvLog.append("\n");
                        tvLog.append("onTokenInvalid:-----------");
                        tvLog.append("\n");
                        tvLog.append(msg);
                        tvLog.append("\n");
                    }
                }));
    }

    private void downloadFile(String url, String sveName){
        String docFilePath = FileConfigManager.getSrtCacheFilePath() + File.separator + sveName;
        // 删除缓存的文件
        FileUtils.clearFolderSubFiles(new File(docFilePath).getParentFile());

        UrlDownloadRequest downloadThread = new UrlDownloadRequest(null, url, docFilePath);
        downloadThread.downloadFile(new UrlDownloadRequest.DownloadCallback() {
            @Override
            public void onDownloadStart(DownloadArg downloadArg) {
            }

            @Override
            public void onDownloadProgress(DownloadArg downloadArg, int progress) {
            }

            @Override
            public void onDownloadError(DownloadArg downloadArg) {
            }

            @Override
            public void onDownloadComplete(DownloadArg downloadArg) {
                if(new File(downloadArg.getTargetFileAbsPaths().get(0)).exists()){
                    Bitmap bitmap = BitmapFactory.decodeFile(downloadArg.getTargetFileAbsPaths().get(0));
                    ivTrans.post(()->{
                        ivTrans.setImageBitmap(bitmap);
                    });
                    tvLog.post(()->{
                        tvLog.append("\n");
                        tvLog.append("onDownloadComplete:-----------");
                        tvLog.append(downloadArg.getTargetFileAbsPaths().get(0));
                        tvLog.append("\n");
                    });

                }
            }
        });
    }
}
